<template>
  <BaseDialog
    title="机器人登录"
    :handleCancel="handleCancel"
    :dialogVisible="props.dialogVisible"
  >
    <div class="code">
      <div v-if="data.loginCode" ref="qrcodeRef"></div>
      <div v-else class="no_data">暂未获取二维码</div>
      <div class="code_text"> 
        {{
          num > 0 && data.codeState == '2'
            ? '二维码已刷新，请使用机器人微信扫码登录'
            : getCodeState(data.codeState)
        }}
      </div>
    </div>
  </BaseDialog>
</template>

<script setup lang="ts">
import QRCode from 'qrcodejs2-fixes'
import BaseDialog from '@/components/base-dialog.vue'
import { basicConfigService } from '@/api/basicConfig'
import { getCodeState } from '@/hooks/getStateName'
const props = defineProps({
  dialogVisible: {
    type: Boolean,
  },
  item: {
    type: Object,
  },
  handleSearch: {
    type: Function,
  },
})
const data = ref({
  codeState: '',
  loginCode: '',
  robotState:1,
})
const qrcodeRef = ref<HTMLElement | null>(null)
const initQrcode = (val = '') => {
  //要生成的内容
  nextTick(() => {
    ;(<HTMLElement>qrcodeRef.value).innerHTML = ''
    new QRCode(qrcodeRef.value, {
      text: val,
      width: 200,
      height: 200,
      colorDark: '#000000',
      colorLight: '#ffffff',
    })
  })
}

const emit = defineEmits(['update:dialogVisible'])
const getCode = () => {
  basicConfigService
    .getRobotInfoDtoByWxRobotId({
      data: props.item.wxRobotId,
    })
    .then((res) => {
      data.value = res.data || {}
      if (data.value.loginCode) { 
        initQrcode(data.value.loginCode)
      }
      if (res.data != null && data.value.robotState!=2) {
        setTimeout(() => {
          handleCancel()
          props.handleSearch()
        }, 3000)
      }
    })
}
const handleCancel = () => {
  emit('update:dialogVisible', false)
}
const num = ref(0)
const timer = ref(null)
onMounted(() => {
  getCode()
  timer.value = setInterval(async () => {
    num.value++
    await getCode()
  }, 5000)
})
onUnmounted(() => {
  clearInterval(timer.value)
})
</script>

<style lang="scss" scoped>
.code {
  @include flex-align-center;
  flex-direction: column;
  .code_text {
    padding-top: 16px;
    color: rgb(245, 154, 35);
    font-size: 20px;
  }
}
.no_data {
  width: 200px;
  height: 200px;
  border: 1px solid #ddd;
  text-align: center;
  line-height: 200px;
}
</style>
